package com.esm.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.esm.service.ChangeStateService;
import com.esm.service.FindSignTimeService;
import com.esm.serviceimpl.ChangeStateServiceImpl;
import com.esm.serviceimpl.FindSignTimeServiceImpl;

import net.sf.json.JSONObject;
/**
 * 
 * @author zyj
 *
 */
public class ChangeStateController extends HttpServlet{
	FindSignTimeService fts=new FindSignTimeServiceImpl();
	ChangeStateService css=new ChangeStateServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String cursgroup=req.getParameter("cursgroup");
		JSONObject signTime=fts.findSignTime(cursgroup);
	    String startTime=signTime.getString("startTime");
		String endTime=signTime.getString("endTime");
		SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String state="";
		try {
			Date startDate=sdf1.parse(startTime);
			Date endDate=sdf2.parse(endTime);
			int startHour=startDate.getHours();
			int endHour=endDate.getHours();
			if(startHour<9 && endHour>=17){
				state="正常";
			}else if(startHour>=9 && endHour>=17){
				state="迟到";
			}else if(startHour<9 && endHour<17){
				state="早退";
			}else{
				state="迟到+早退";
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//根据签到签退时间改变签到的状态
		boolean stateFlag=css.changeState(cursgroup, state);
		
		//写回前端
		JSONObject j=new JSONObject();
		j.put("state", state);
		j.put("stateFlag", stateFlag);
		PrintWriter pw=resp.getWriter();
		pw.write(j.toString());
		pw.flush();
		pw.close();
	}
	
}
